package face.pay.cpn.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;
import face.pay.AbstractRedis;
import face.pay.constant.CacheKey;
import face.pay.cpn.service.IGetCouponService;
import face.pay.dao.CpnCardDetailInfoDao;
import face.pay.dao.CpnOemWxInfoDao;
import face.pay.dao.CpnWxAppInfoDao;
import face.pay.entity.CpnCardDetailInfo;
import face.pay.entity.CpnOemWxInfo;
import face.pay.entity.CpnWxAppInfo;
import face.pay.util.AESUtils;
import face.pay.util.DateUtil;
import face.pay.util.JSSDK_Config;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GetCouponServiceImpl implements IGetCouponService {


    @Autowired
    CpnWxAppInfoDao cpnWxAppInfoDao;

    @Autowired
    CpnCardDetailInfoDao cpnCardDetailInfoDao;

    @Autowired
    AbstractRedis redisUtils;

    @Override
    public String getCpn(String cpn_auth_code, Model model, HttpServletRequest request) throws Exception {
        String domain =   request.getServerName();
        log.info("访问域名："+domain);
        log.info("cpn_auth_code："+cpn_auth_code);
        CpnWxAppInfo cpnWxAppInfo =  this.cpnWxAppInfoDao.getById(1);

        if(cpnWxAppInfo!=null){
            String appid =cpnWxAppInfo.getAppId();

            String redirect_uri = "http://"+domain+"/cpnAuth";
            String url =  "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}&connect_redirect=1#wechat_redirect";
            url =  MessageFormat.format(url,appid,redirect_uri,cpn_auth_code);
            return  url;
        }else {
            throw new Exception("域名未注册");
        }

    }

    @Override
    public Boolean cpnAuth(String code, String state, Model model, HttpServletRequest request) {

        CpnCardDetailInfo cpnCardDetailInfo =  new CpnCardDetailInfo();

        String errorMessage = "";

        Boolean isSuccess = false;


        String domain =   request.getServerName();
        log.info("访问域名："+domain);

        String json  =  (String) redisUtils.get(CacheKey.WX_APP_INFO);
        CpnWxAppInfo cpnWxAppInfo = JSON.parseObject(json,CpnWxAppInfo.class);


        if(cpnWxAppInfo!=null){

            log.info("获取oem服务商优惠券兑换 微信配置信息："+cpnWxAppInfo.toString());
            String cpnCode = state;
            log.info("cpnCode："+cpnCode);
            /**
             *cpnCode
             */
            if(StringUtils.isNotBlank(cpnCode)){
            log.info("解码后 cpnCode："+cpnCode);

            cpnCardDetailInfo =  this.cpnCardDetailInfoDao.getByCpnCode(cpnCode);

            Integer status = cpnCardDetailInfo.getStatus();

            if(new Integer(0).equals(status)){
                String appid = cpnWxAppInfo.getAppId();
                String secret = cpnWxAppInfo.getSecret();
                SnsToken snsToken =  SnsAPI.oauth2AccessToken(appid,secret,code);
                String openId = snsToken.getOpenid();
                cpnCardDetailInfo.setCenterOpenId(openId);

                cpnCardDetailInfoDao.upOpenId(cpnCardDetailInfo);

                Map<String,String> extJsonData = new HashMap<>();


                String timestamp = DateUtil.getSecondTimestamp(new Date());
                String card_id = cpnCardDetailInfo.getWxCardId();
                String  outer_str = String.valueOf(cpnCardDetailInfo.getId());
                String nonce_str = WXPayUtil.generateNonceStr();

                String cardTicket = cpnWxAppInfo.getCardTicket();


                extJsonData.put("timestamp",timestamp);
                extJsonData.put("card_id",card_id);
                extJsonData.put("nonce_str",nonce_str);
                extJsonData.put("api_ticket",cardTicket);

                String[] signArray = new String[]{
                        timestamp,
                        card_id,
                        nonce_str,
                        cardTicket
                       };

                String signString = WXPayUtil.getSortString(signArray);
                String signature = WXPayUtil.SHA1(signString);
                extJsonData.put("signature",signature);

                extJsonData.remove("card_id");
                log.error(extJsonData.toString());
                extJsonData.put("outer_str",outer_str);

                model.addAttribute("extJson",JSON.toJSONString(extJsonData) );

                isSuccess = true;
            }else {
                errorMessage = "优惠券已已经领取";
            }
            }else {
                errorMessage="优惠券cpn_auth_code错误";
            }

        }else {
            errorMessage = "获取用户资料失败";
        }


        model.addAttribute("errorMessage",errorMessage);
        model.addAttribute("isSuccess",isSuccess);
        model.addAttribute("cpnCodeInfo",cpnCardDetailInfo);

        return  isSuccess;
    }
}
